$(function () {
    $("#jqGrid").jqGrid({
        url: '../cashiers/list',
        datatype: "json",
        colModel: [			
			{ label: '姓名', name: 'name', index: 'name', width: 60 }, 			
			{ label: '手机号码', name: 'mobilePhone', index: 'mobilephone', width: 60 }, 	
			{ label: '所属单位', name: 'shopName', index: 'm.shopname', width: 140 },
			{ label: '商户号', name: 'merchantId', index: 'merchantId', width: 100 },
			{ label: '角色', name: 'role', index: 'role', width: 60 ,
				formatter: function(value, options, row){
					if(value == 1){
						return '管理员';
					}else if(value == 2){
						return '收款员';
					}
					else{
						return '';
					}
				}
			},
			{ label: '状态', name: 'activateState', index: 'activateState', width: 60,
				formatter: function(value, options, row){
					if(value == 0){
						return '<span class="label" style="background-color: #f39c12">未激活</span>';
					}
					if(value == 1){
						return '<span class="label label-success">已激活</span>';
					}
					if(value == 2){
						//return '<span class="label label-danger">已删除</span>';
						return '<span class="label " style="background-color: #777">已删除</span>';
						
					}else{
						return '';
					}
				}			
			},
			{ label: '二维码', name: 'qrCode', index: 'activateState', width: 60,sortable : false,
				formatter: function(value, options, row){
					var userId = row.id;
					if(value == 'true'){
						return '<a onclick="showInfo(' + userId+ ')" target="view_window"><span class="label label-success" >预览</span></a>';
					}else{
						return '暂无二维码';
					}
				} 	
			},
			{ label: '邀请码', name: 'inviteCode', index: 'inviteCode', width: 65,sortable : false }, 
        ],
		viewrecords: true,
        height: 'auto',
		//shrinkToFit: true,
        rowNum: 10,
		rowList : [10,20,30],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ 'overflow-y' : "hidden" });
        },
        onSelectAll:function(rowids,status){
        	//alert(rowids +'--------------'+ status);
        }
    });
    
 	  
  //根据商户号获取商户信息下拉
    $.ajax({
    	type: "POST",
	    url: "../merchantinfo/getMerchantInfoSelect",
	    success: function(result){
	    	var list = result.options;
	    	if(list != null){
	    		for(var i=0;i < list.length ;i++){
		    		var obj = {};
		    		obj = list[i];
		    		vm.merchantOptions[i] = obj;
		    	}
	    	}
		}
	});
});

function pageSize() { 
	  var winW, winH; 
	  if(window.innerHeight) {// all except IE 
	   winW = window.innerWidth; 
	   winH = window.innerHeight; 
	  }else if (document.documentElement && document.documentElement.clientHeight) {// IE 6 Strict Mode
	   winW = document.documentElement.clientWidth; 
	   winH = document.documentElement.clientHeight; 
	  }else if (document.body) { // other 
	   winW = document.body.clientWidth; 
	   winH = document.body.clientHeight; 
	  }  // for small pages with total size less then the viewport 
	  return {WinW:winW, WinH:winH}; 
}
function showInfo(userId){
	parent.layer.open({
		  type: 2,
		  title: '二维码列表',
		  shadeClose: true,
		  shade: 0.8,
		  fixed: false, //不固定
		  maxmin: true,
		  area: ['60%', '80%'],
		  //content: 'merchant/listQRCode.html?id='+id //iframe的url
		  content: 'cashiers/getCodeList.do?userId='+userId //iframe的url
		}); 
}

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			shopName: null
		},
		showList: true,
		title: null,
		cashiers: {},
		selected: '',
	    statusOptions:[
	    	{text:"未激活",value:"0"},
	    	{text:"已激活",value:"1"},
	    	{text:"已删除",value:"2"}
	    ],
	    roleList:{text:"管理员",value:"1",text:"收款员",value:"2"},
	    merchantOptions:[],
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.cashiers = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id);
		},
		saveOrUpdate: function (event) {
			var url = vm.cashiers.id == null ? "../cashiers/save" : "../cashiers/update";
			$("#submitBtn").attr("disabled","disabled"); 
			var merchantId = vm.cashiers.merchantId;
			if(merchantId == null || "" == merchantId){
				alert('请选择一个企业');
				return;
			}
			var name = vm.cashiers.name;
			if(name == null || "" == name){
				alert('收款员姓名不能为空');
				return;
			}
			
			var mobile = vm.cashiers.mobilePhone;
			if(mobile == null || "" == mobile){
				alert('手机号码不能为空');
				return;
			}
			if (!(/^((\d{3}-\d{8}|\d{4}-\d{7,8})|(1[3|5|7|8][0-9]{9}))$/.test(mobile))) {
	             alert("手机号码填写的格式不对，请正确填写");
	             return false;
			}
			
			var role = vm.cashiers.role;
			if(role == null || "" == role){
				alert('请选择一个角色');
				return;
			}
			
			var authority = vm.cashiers.authority;
			//var authority = $('#authority').val();
			if(authority == null || "" == authority){
				alert('请选择一个退款权限');
				return;
			}
			
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.cashiers),
			    success: function(r){
			    	if(r.code == 0){
						alert(r.msg, function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
			    	$("#submitBtn").removeAttr("disabled");
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../cashiers/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get("../cashiers/info/"+id, function(r){
                vm.cashiers = r.cashiers;
            });
		},
		view: function(id){
			
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			page = 1;
			var keyword = $("#keyword").val();
			var mobilePhone = $("#mobilePhone").val();
			var status = $("#status").val();
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{
                	keyword:keyword,
                    mobilePhone:mobilePhone,
                	status:status},
            }).trigger("reloadGrid");
		},
		recovery: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			confirm('确定要恢复选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../cashiers/recovery",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		codeList: function(event){
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			var rowData = $('#jqGrid').jqGrid('getRowData',id);
			if(rowData.activateState == '未激活'){
				alert("该收款员未激活，请激活后在执行此操作");
				return ;
			}
			parent.layer.open({
				  type: 2,
				  title: '二维码信息',
				  shadeClose: true,
				  shade: 0.8,
				  fixed: false, //不固定
				  maxmin: true,
				  area: ['80%', '80%'],
				  content: 'qrCode/codeList.html?userId='+id+"&merchantNo="+rowData.merchantId //iframe的url
				});
		},
        contrast: function(event){
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            var bool=false;
            ss = ids.toString().split(",");
            for(var i=0;i<ss.length;i++){
                var rowData = $('#jqGrid').jqGrid('getRowData',ss[i]);
                //console.log(ss[i]+"===="+rowData.activateState);
                if(rowData.activateState == "<span class=\"label\" style=\"background-color: #f39c12\">未激活</span>"){
                    bool=true;
                }
            }
            if(bool){
                alert("选项中包含未激活收款员，请移除未激活收款员！");
                return ;
            }
            parent.layer.open({
                type: 2,
                title: '收款员交易对比',
                shadeClose: true,
                shade: 0.8,
                fixed: false, //不固定
                maxmin: true,
                area: ['88%', '80%'],
                content: "cashiers/contrast.html?userIds="+ids
            });
        }
	}
});